import {
  Form,
  Button,
  DatePicker,
  Radio,
  Select,
  Steps,
  Input,
  Row,
  Col,
  Select,
  InputNumber,
  Table,
  message,
} from 'antd';
import React, {Component} from 'react';
import {FormComponentProps} from 'antd/es/form';
import {TableListItem} from '../data.d';
import moment from 'moment';

const FormItem = Form.Item;
const {Step} = Steps;
const {TextArea} = Input;
const {Option} = Select;
const RadioGroup = Radio.Group;
import validator from '@/utils/Validator';
import BizParams from '../utils/BizParams.tsx';
import CurrencySelect from '../utils/CurrencySelect.tsx';
import Constants from '../utils/Constants';
import SingleDragger from '../../../../../../components/Commons/SingleDragger';

const R = require('ramda');
import {connect} from 'dva';

export interface FormValsType extends Partial<TableListItem> {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
}

export interface UpdateFormProps extends FormComponentProps {
  handleUpdateModalVisible: (flag?: boolean, formVals?: FormValsType) => void;
  handleModalVisible: (values: FormValsType) => void;
  updateModalVisible: boolean;
  values: Partial<TableListItem>;
}

export interface UpdateFormState {
  formVals: FormValsType;
}

const orderForm = Form.create()(
  class OrderForm extends React.Component {
    static defaultProps = {
      handleModalVisible: () => {
      },
      handleUpdateModalVisible: () => {
      },
      values: {},
    };

    constructor(props: UpdateFormProps) {
      super(props);
      this.state = {
        productflag: false, //产品列表数据
        showFreight: false,
        showPremium: false,
        productList: [],
      };
    }

    statistics = {};

    handleResetFields = () => {
      this.props.form.resetFields();
      const {dispatch, handleModalVisible, handleSearch} = this.props;
      dispatch({
        type: 'invoiceManagement/refreshState',
        payload: {
          drawerList: {},
        },
      });
      handleModalVisible(false);
      handleSearch();
    };

    handleChangePriceClause = value => {
      if (value === '1') {
        this.setState({showPremium: true});
        this.setState({showFreight: true});
      }
      if (value === '2') {
        this.props.form.setFieldsValue({premium: 0, premiumcurrency: ''});
        this.setState({showPremium: false});
        this.setState({showFreight: true});
      }
      if (value === '4') {
        this.props.form.setFieldsValue({freight: 0, freightcurrency: ''});
        this.setState({showPremium: true});
        this.setState({showFreight: false});
      }
      if (value !== '1' && value !== '2' && value !== '4') {
        //不是CIF，先清理保费
        this.props.form.setFieldsValue({freight: 0, freightcurrency: ''});
        //不是C&F，再清理运费
        this.props.form.setFieldsValue({premium: 0, premiumcurrency: ''});
        this.setState({showFreight: false});
        this.setState({showPremium: false});
      }
    };

    handleOpenAddProduct = () => {
      const {dispatch, orderProductDetails} = this.props;
      dispatch({
        type: 'invoiceManagement/queryProductList',
        payload: {
          productPage: Constants.DEFAULT_PAGE,
        },
      });
      if (!this.state.productflag) {
        this.setState({productList: orderProductDetails, productflag: true});
      }
      this.formRef.handleOpen();
    };

    handleChangeProductNumber = (record, value) => {
      const {orderProductDetails} = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }
      let customer = R.isNil(this.props.customer) ? {} : this.props.customer;
      let agencyfee = R.isNil(customer.agencyfee) ? 0 : customer.agencyfee / 100; //费率
      let retrodictRate = R.isNil(this.props.form.getFieldValue('retrodictrate'))
        ? 0
        : this.props.form.getFieldValue('retrodictrate');
      R.map(row => {
        if (row.id === record.id) {
          row.productnumber = value;
          row.productweight = Math.round(value * row.singleweight * 10000) / 10000;
          if (this.state.retrodictRate && retrodictRate !== agencyfee) {
            //倒推 数量联动单价
            let draweramount =
              R.isNil(row.draweramount) || R.isEmpty(row.draweramount) ? 0 : row.draweramount; //倒推开票金额默认为0
            let retrodictcost =
              R.isNil(row.retrodictcost) || R.isEmpty(row.retrodictcost) ? 0 : row.retrodictcost; //倒推费用默认为0
            let productnumber =
              R.isNil(row.productnumber) || R.isEmpty(row.productnumber) ? 1 : row.productnumber; //数量默认为1
            row.productprice = (
              ((draweramount * (1 + row.zzrate / 100 - row.taxrate / 100)) /
                (1 + row.zzrate / 100) +
                retrodictcost) /
              (retrodictRate - agencyfee) /
              productnumber
            ).toFixed(4);
          }
          row.totalprice = Math.round(row.productprice * row.productnumber * 100) / 100;
        }
      }, productList);
      this.setState({productList: productList});
    };

    handleChangePackageNumber = (record, value) => {
      const {orderProductDetails} = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }
      R.map(row => {
        if (row.id === record.id) {
          row.packagenumber = value;
        }
      }, productList);
      this.setState({productList: productList});
    };

    handleChangeProductPrice = (record, value) => {
      const {orderProductDetails} = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }
      R.map(row => {
        if (row.id === record.id) {
          row.productprice = value;
          row.totalprice = Math.round(value * row.productnumber * 100) / 100;
        }
      }, productList);
      this.setState({productList: productList});
    };

    handleChangeProductWeight = (record, value) => {
      const {orderProductDetails} = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }
      R.map(row => {
        if (row.id === record.id) {
          row.productweight = value;
        }
      }, productList);
      this.setState({productList: productList});
    };

    handleChangeGrossWeight = (record, value) => {
      const {orderProductDetails} = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }
      R.map(row => {
        if (row.id === record.id) {
          row.grossweight = value;
        }
      }, productList);
      this.setState({productList: productList});
    };

    drawerMap = {};
    handleChangeDrawer = (record, value) => {
      const {orderProductDetails} = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }
      R.map(row => {
        if (row.id === record.id) {
          row.drawerid = value;
          row.drawername = this.drawerMap[value];
        }
      }, productList);
      this.setState({productList: productList});
    };

    handleChangeProductSize = (record, e) => {
      const {orderProductDetails} = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = orderProductDetails;
        this.setState({productflag: true});
      } else {
        productList = R.clone(this.state.productList);
      }
      R.map(row => {
        if (row.id === record.id) {
          row.productsize = e.target.value;
        }
      }, productList);
      this.setState({productList: productList});
    };

    handleDeleteProduct = record => {
      const {orderProductDetails} = this.props;

      let productList = [];
      if (!this.state.productflag) {
        productList = R.difference(orderProductDetails, [record]);
        this.setState({productflag: true});
      } else {
        productList = R.difference(this.state.productList, [record]);
      }
      this.setState({productList: productList, retrodictFlag: true});
    };

    handleInitColumns = () => {
      return R.without(
        [null],
        [
          {title: '品名', dataIndex: 'productname', key: 'productname'},
          {title: '型号', dataIndex: 'productmodel', key: 'productmodel'},
          {title: '品牌类型', dataIndex: 'productbranchname', key: 'productbranchname'},
          {title: '品牌', dataIndex: 'productbranch', key: 'productbranch'},
          {title: '币种', dataIndex: 'productcurrency', key: 'productcurrency'},
          {
            title: '数量',
            dataIndex: 'productnumber',
            key: 'productnumber',
            render: (text, record, index) => {
              return (
                <InputNumber
                  min={0}
                  max={99999999999999}
                  value={record.productnumber}
                  onChange={this.handleChangeProductNumber.bind(this, record)}
                />
              );
            },
          },
          {title: '单位', dataIndex: 'productunit', key: 'productunit'},
          {
            title: '包装件数',
            dataIndex: 'packagenumber',
            key: 'packagenumber',
            render: (text, record, index) => {
              return (
                <InputNumber
                  min={0}
                  max={99999999999999}
                  value={record.packagenumber}
                  onChange={this.handleChangePackageNumber.bind(this, record)}
                />
              );
            },
          },
          {
            title: '单价',
            dataIndex: 'productprice',
            key: 'productprice',
            render: (text, record, index) => {
              return (
                <InputNumber
                  min={0}
                  max={99999999999999}
                  value={record.productprice}
                  onChange={this.handleChangeProductPrice.bind(this, record)}
                />
              );
            },
          },
          {title: '单净重(Kg)', dataIndex: 'singleweight', key: 'singleweight'},
          {
            title: '净重(Kg)',
            dataIndex: 'productweight',
            key: 'productweight',
            render: (text, record, index) => {
              return (
                <InputNumber
                  min={0}
                  max={99999999999999}
                  value={record.productweight}
                  onChange={this.handleChangeProductWeight.bind(this, record)}
                />
              );
            },
          },
          {
            title: '毛重(Kg)',
            dataIndex: 'grossweight',
            key: 'grossweight',
            render: (text, record, index) => {
              return (
                <InputNumber
                  min={0}
                  max={99999999999999}
                  value={record.grossweight}
                  onChange={this.handleChangeGrossWeight.bind(this, record)}
                />
              );
            },
          },
          {
            title: '关联开票人',
            dataIndex: 'drawername',
            key: 'drawername',
            render: (text, record, index) => {
              return (
                <Select
                  style={{width: '100%'}}
                  value={record.drawerid + ''}
                  onChange={this.handleChangeDrawer.bind(this, record)}
                >
                  {!R.isNil(this.props.drawersList)
                    ? this.props.drawersList.map(item => {
                      if (!R.contains(item.id)(this.drawerMap))
                        this.drawerMap[item.id] = item.name;
                      return (
                        <Select.Option value={item.id + ''} key={item.id + ''}>
                          {item.name}: {item.taxplayercode}
                        </Select.Option>
                      );
                    })
                    : ''}
                </Select>
              );
            },
          },
          {title: '货值', dataIndex: 'totalprice', key: 'totalprice'},
          {
            title: '规格',
            dataIndex: 'productsize',
            key: 'productsize',
            render: (text, record, index) => {
              return (
                <Input
                  maxLength="1000"
                  style={{width: 'auto'}}
                  value={R.isNil(record.productsize) ? '' : record.productsize}
                  onChange={this.handleChangeProductSize.bind(this, record)}
                />
              );
            },
          },
          {title: '申报参数', dataIndex: 'productdeclarelements', key: 'productdeclarelements'},
          {title: '退税率', dataIndex: 'taxrate', key: 'taxrate'},
          {title: '增值税率', dataIndex: 'zzrate', key: 'zzrate'},
          {
            title: '操作',
            key: 'operation',
            fixed:'right',
            render: (text, record, index) => {
              return (
                <div>
                  <a href="#" onClick={this.handleDeleteProduct.bind(this, record)}>
                    删除
                  </a>
                </div>
              );
            },
          },
        ],
      );
    };

    getForm = () => {
      const {form, dispatch, handleSave, recordFormValues} = this.props;
      let url1 = this.refs.certInfoReceipt.getUrl();
      let url2 = this.refs.certInfoTaxRegister.getUrl();
      let url3 = this.refs.certInfoTaxplayer.getUrl();
      let url4 = this.refs.certInfoBussinessLicense.getUrl();
      let url5 = this.refs.certInfoSaleCheck.getUrl();
      let url6 = this.refs.certInfoVATVoice.getUrl();
      let url7 = this.refs.certInfoProtocal.getUrl();
      let url8 = this.refs.certInfoOther.getUrl();
      let updatetime = null;
      let identifitime = null;
      form.validateFields((err, fieldsValue) => {
        updatetime = moment(fieldsValue['updatetime']).format('YYYY-MM-DD');
        identifitime = moment(fieldsValue['identifitime']).format('YYYY-MM-DD');
        if (err) return;
        const formVals = {...fieldsValue};
        formVals.certInfoReceipt = url1;
        formVals.certInfoTaxRegister = url2;
        formVals.certInfoTaxplayer = url3;
        formVals.certInfoBussinessLicense = url4;
        formVals.certInfoSaleCheck = url5;
        formVals.certInfoVATVoice = url6;
        formVals.certInfoProtocal = url7;
        formVals.certInfoOther = url8;
        handleSave(formVals);
      });
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        let flag = true;
        if (flag) {
          let dataSource = {...fieldsValue, ...this.statistics};
          dataSource.updatetime = updatetime;
          dataSource.identifitime = identifitime;
          dataSource.certInfoReceipt = url1;
          dataSource.certInfoTaxRegister = url2;
          dataSource.certInfoTaxplayer = url3;
          dataSource.certInfoBussinessLicense = url4;
          dataSource.certInfoSaleCheck = url5;
          dataSource.certInfoVATVoice = url6;
          dataSource.certInfoProtocal = url7;
          dataSource.certInfoOther = url8;

          let fun = '';
          if (recordFormValues.id) {
            fun = 'invoiceManagement/updateDrawer';
            dataSource.id = recordFormValues.id;
          } else {
            fun = 'invoiceManagement/createDrawer';
          }

          dispatch({
            type: fun,
            payload: {
              dataSource,
              onSuccess: () => {
                this.handleResetFields();
              },
              onFail: () => {
                this.handleResetFields();
              },
            },
          });
        }
      });
    };

    handleAddProducts = tempProductList => {
      this.setState({productList: R.concat(this.state.productList, tempProductList)});
    };

    render() {
      const {
        form: {getFieldDecorator, getFieldValue},
        privateCstList,
        buyerList,
        supplygoodList,
        drawerList,
        orderTgApproval,
        orderProductDetails,
        recordFormValues,
      } = this.props;

      const formItemLayout = {
        labelCol: {
          xs: {span: 24},
          sm: {span: 7},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 12},
          md: {span: 10},
        },
      };

      let attachments = R.isNil(drawerList.attachments) ? {} : drawerList.attachments;
      let certInfoReceipt = R.isNil(attachments.certInfoReceipt)
        ? ''
        : attachments.certInfoReceipt.url;
      let certInfoTaxRegister = R.isNil(attachments.certInfoTaxRegister)
        ? ''
        : attachments.certInfoTaxRegister.url;
      let certInfoTaxplayer = R.isNil(attachments.certInfoTaxplayer)
        ? ''
        : attachments.certInfoTaxplayer.url;
      let certInfoBussinessLicense = R.isNil(attachments.certInfoBussinessLicense)
        ? ''
        : attachments.certInfoBussinessLicense.url;
      let certInfoSaleCheck = R.isNil(attachments.certInfoSaleCheck)
        ? ''
        : attachments.certInfoSaleCheck.url;
      let certInfoVATVoice = R.isNil(attachments.certInfoVATVoice)
        ? ''
        : attachments.certInfoVATVoice.url;
      let certInfoProtocal = R.isNil(attachments.certInfoProtocal)
        ? ''
        : attachments.certInfoProtocal.url;
      let certInfoOther = R.isNil(attachments.certInfoOther) ? '' : attachments.certInfoOther.url;
      return (
        <div>
          <Form style={{marginTop: 8}}>
            <Row gutter={24}>
              <Col xs={24} md={12}>
                <FormItem label={<span>开票工厂名称</span>}>
                  {getFieldDecorator('name', {
                    rules: [{required: true, message: '请填写开票工厂名称！'}],
                    initialValue: drawerList.name,
                  })(<Input placeholder="请填写开票工厂名称"/>)}
                </FormItem>
              </Col>
              <Col xs={24} md={6}>
                <FormItem label={<span>纳税人识别号</span>}>
                  {getFieldDecorator('taxplayercode', {
                    rules: [{required: true, message: '请填写订纳税人识别号！'}],
                    initialValue: drawerList.taxplayercode,
                  })(<InputNumber placeholder="请输入纳税人识别号" style={{width: '100%'}}/>)}
                </FormItem>
              </Col>
              <Col xs={24} md={6}>
                <FormItem label={<span>一般纳税人认定时间</span>}>
                  {getFieldDecorator('identifitime', {
                    rules: [{required: true, message: '请填写一般纳税人认定时间'}],
                    initialValue: drawerList.identifitime
                      ? moment(drawerList.identifitime.toString(), 'YYYY-MM-DD')
                      : undefined,
                  })(<DatePicker style={{width: '100%'}}/>)}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col xs={24} md={6}>
                <FormItem label={<span>预计月均出口额（万）</span>}>
                  {getFieldDecorator('exportvolume', {
                    rules: [{required: true, message: '请填写预计月均出口额！'}],
                    initialValue: drawerList.exportvolume,
                  })(<InputNumber placeholder="请填写预计月均出口额" style={{width: '100%'}}/>)}
                </FormItem>
              </Col>

              <Col xs={24} md={6}>
                <FormItem label={<span>出口额币种</span>}>
                  {getFieldDecorator('exportvolumecurrency', {
                    rules: [{required: true, message: '请选择报关币种！'}],
                    initialValue: drawerList.exportvolumecurrency,
                  })(<CurrencySelect/>)}
                </FormItem>
              </Col>

              <Col xs={24} md={6}>
                <FormItem label={<span>境内货源地</span>}>
                  {getFieldDecorator('supplygoods', {
                    rules: [
                      {
                        required: true,
                        message: '请选择境内货源地！',
                      },
                    ],
                    initialValue: drawerList.supplygoods,
                  })(<BizParams sprCode={'supplyGoods'} disabled={false}/>)}
                </FormItem>
              </Col>
              <Col xs={24} md={6}>
                <FormItem label={<span>厂房面积</span>}>
                  {getFieldDecorator('workshop', {
                    rules: [{required: true, message: '请填写厂房面积！'}],
                    initialValue: drawerList.workshop,
                  })(<InputNumber placeholder="请填写厂房面积" style={{width: '100%'}}/>)}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col xs={24} md={12}>
                <FormItem label={<span>开票工厂地址</span>}>
                  {getFieldDecorator('address', {
                    rules: [{required: true, message: '请填写开票工厂地址！'}],
                    initialValue: drawerList.address,
                  })(<Input placeholder="请填写开票工厂地址"/>)}
                </FormItem>
              </Col>
              <Col xs={24} md={6}>
                <FormItem label={<span>员工人数</span>}>
                  {getFieldDecorator('staffnum', {
                    rules: [{required: true, message: '请填写员工人数！'}],
                    initialValue: drawerList.staffnum,
                  })(<InputNumber placeholder="请填写员工人数" style={{width: '100%'}}/>)}
                </FormItem>
              </Col>
              <Col xs={24} md={6}>
                <FormItem label={<span>成立日期</span>}>
                  {getFieldDecorator('updatetime', {
                    rules: [{required: true, message: '请填写成立日期'}],
                    initialValue: drawerList.updatetime
                      ? moment(drawerList.updatetime.toString(), 'YYYY-MM-DD')
                      : undefined,
                  })(<DatePicker style={{width: '100%'}}/>)}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col xs={24} md={6}>
                <FormItem label={<span>联系人</span>}>
                  {getFieldDecorator('contactname', {
                    rules: [{required: true, message: '请填写联系人！'}],
                    initialValue: drawerList.contactname,
                  })(<Input placeholder="请填写联系人"/>)}
                </FormItem>
              </Col>
              <Col xs={24} md={6}>
                <FormItem label={<span>联系电话</span>}>
                  {getFieldDecorator('contacttel', {
                    initialValue: drawerList.contacttel,
                  })(<InputNumber placeholder="请填写联系电话" style={{width: '100%'}}/>)}
                </FormItem>
              </Col>
              <Col xs={24} md={12}>
                <FormItem label={<span>备注</span>}>
                  {getFieldDecorator('memo', {
                    initialValue: drawerList.memo,
                  })(<Input placeholder="请填写备注"/>)}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col xs={24} md={6}>
                <FormItem label="销项发票" hasFeedback>
                  <SingleDragger
                    ref="certInfoReceipt"
                    url={certInfoReceipt}
                    dataSource={attachments}
                    module={'drawer'}
                  />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label="销项发税务登记证副本" hasFeedback>
                  <SingleDragger
                    ref="certInfoTaxRegister"
                    url={certInfoTaxRegister}
                    dataSource={attachments}
                    module={'drawer'}
                  />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label="一般纳税人认定书" hasFeedback>
                  <SingleDragger
                    ref="certInfoTaxplayer"
                    url={certInfoTaxplayer}
                    dataSource={attachments}
                    module={'drawer'}
                  />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label="营业执照副本" hasFeedback>
                  <SingleDragger
                    ref="certInfoBussinessLicense"
                    url={certInfoBussinessLicense}
                    dataSource={attachments}
                    module={'drawer'}
                  />
                </FormItem>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col span={6}>
                <FormItem label="销售验厂情况" hasFeedback>
                  <SingleDragger
                    ref="certInfoSaleCheck"
                    url={certInfoSaleCheck}
                    dataSource={attachments}
                    module={'drawer'}
                  />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label="进项发票" hasFeedback>
                  <SingleDragger
                    ref="certInfoVATVoice"
                    url={certInfoVATVoice}
                    dataSource={attachments}
                    module={'drawer'}
                  />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label="外贸出口协议" hasFeedback>
                  <SingleDragger
                    ref="certInfoProtocal"
                    url={certInfoProtocal}
                    dataSource={attachments}
                    module={'drawer'}
                  />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label="其他" hasFeedback>
                  <SingleDragger
                    ref="certInfoOther"
                    url={certInfoOther}
                    dataSource={attachments}
                    module={'drawer'}
                  />
                </FormItem>
              </Col>
            </Row>
            <Row gutter={24}>
              <Row style={{margin: '0 auto'}}>
                <FormItem style={{display: 'flex', justifyContent: 'center'}}>
                  <Button
                    key="forward"
                    type="primary"
                    loading={this.props.loading}
                    onClick={() => this.getForm()}
                  >
                    保存开票工厂
                  </Button>
                  <Button
                    key="cancel"
                    style={{marginTop: 8, marginLeft: 8}}
                    onClick={() => this.handleResetFields()}
                  >
                    取消
                  </Button>
                </FormItem>
              </Row>
            </Row>
          </Form>
        </div>
      );
    }
  },
);

function mapStateToProps(state) {
  return {
    loading: state.loading.models.invoiceManagement,
  };
}

export default connect(mapStateToProps)(orderForm);
